﻿// version 1.1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;


namespace pi
{
    class Program
    {
        static void Main(string[] args)
        {
            UInt64 cnt = 0;
            UInt64 sum = 0;
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] b2 = new byte[2];
            byte[] b4 = new byte[4]{0,0,0,0};
            UInt64 n1, n2;

            Program p = new Program();

            // calculate pi from chaos :)
            for(uint i=0;i<1000;i++)
            {
                // one byte
                rng.GetBytes(b2);
                n1 = b2[0];
                n2 = b2[1];
                
                // two bytes
                /*rng.GetBytes(b2);
                b2.CopyTo(b4, 0);
                n1=BitConverter.ToUInt32(b4, 0);
                rng.GetBytes(b2);
                b2.CopyTo(b4, 0);
                n2 = BitConverter.ToUInt32(b4, 0);*/
                
                n1++; n2++; // don't use zero
                //sum += p.NotHaveCommonDivisor(n1, n2);
                sum += p.NotHaveCommonDivisor(n1+756, n2+1234567);
                cnt++;
            }

            double quotient = (double)sum / (double)cnt;
            Console.WriteLine("cnt: {0}\nsum: {1}\npi:  {2}", 
                sum, 
                cnt, 
                Math.Round(Math.Sqrt(6 / quotient), 6, MidpointRounding.AwayFromZero));
            Console.ReadLine();
        }

        //-------------------------------------------

        private UInt64 NotHaveCommonDivisor(UInt64 n1, UInt64 n2)
        {
            UInt64 min = Math.Min(n1, n2);

            for (UInt64 i = 2; i < min; i++)
                if (n1 % i == 0 && n2 % i == 0) return 0;   // n1 and n2 have common divisor

            return 1;   // n1 and n2 do not have common divisor
        }
    }
}
